package cn.biplam.front.component.view.systemManage.task.process;

import java.util.ArrayList;

import cn.biplam.common.client.DataFilter;
import cn.biplam.common.client.Operator;
import cn.biplam.common.client.OperatorResult;
import cn.biplam.common.opcode.SysManageCode.FileUploadOptCode;
import cn.biplam.common.runtime.Task;
import cn.biplam.common.runtime.TaskBase;
import cn.biplam.common.struc.SysStruc.FileUpLoadStru;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;
import cn.biplam.common.wrapper.UserInfo;
import cn.biplam.common.wrapper.sqlresult.SqlResult;
import cn.biplam.front.component.data.common.ButtonComp;
import cn.biplam.front.component.view.systemManage.task.TaskProcessMain;
import cn.biplam.front.html.HtmlDiv;
import cn.biplam.front.html.HtmlValue;
import cn.biplam.front.html.base.HtmlWindow;
import cn.biplam.front.html.base.Const.Length_Unit;
import cn.biplam.front.html.base.Const.Visibility_Mode;
import cn.biplam.front.htmlscript.script.AjxScript;
import cn.biplam.front.htmlscript.script.PopupScript;
import cn.biplam.front.htmlscript.script.ScriptBind;
import cn.biplam.front.template.base.FileDownLoad;
import cn.biplam.front.template.base.HiddenParams;
import cn.biplam.front.template.base.TextArea;
import cn.biplam.front.template.base.Button.Button_Type;
import cn.biplam.front.template.base.FileDownLoad.File_Src;
import cn.biplam.front.template.control.FlatTable;

/**
 * 显示后台任务的执行信息
 * @author WangSong 2009-7-25下午02:40:58
 * @version 1.0
 */
public class TaskProcess {

	private String ID;
	private UserInfo mUser;
	private boolean buttonShow = false;
	@SuppressWarnings("unused")
	private int time=2000;
	private String parentCid;
	private String parentAid;

	private String returnBtId = "rBt_Id";
	private String processInfoArearID = null;
	private String refreshFlagID = null;
	private String containerID = "myRefresh";
	/** 任务提示记录*/
	private static KvMap<String,Integer> taskPrompt;

	/**
	 * 构造方法
	 * @param ID   标识ID
	 * @param mUser 用户信息
	 * @param refeshActionId 刷新页面的actionId
	 * @param popLevel 弹出窗口的级别
	 */
	public TaskProcess(String ID,UserInfo mUser){
		this.ID = ID+"process";
		this.mUser = mUser;
		this.processInfoArearID = ID+"show";
		this.refreshFlagID = "refResh_flag";
		if(taskPrompt==null){
			taskPrompt = new KvMap<String, Integer>();
		}
	}

	/**
	 * 设置页面刷新的时间间隔(毫秒级)
	 * @param time 刷新的时间间隔(毫秒级)
	 */
	public void setRefreshInterval(int time){
		this.time = time;
	}

	/**
	 * 设置任务执行完后，刷新的父页面信息
	 * @param cId 父页面容器ID
	 * @param aId 父页面行为ID
	 */
	public void setRefreshParentInfo(String cId,String aId){
		this.parentCid = cId;
		this.parentAid = aId;
	}

	/**
	 * 取导入任务
	 * @param taskId
	 * @param fileId下载文件Id
	 * @return
	 * @throws ErrorMessage
	 */
	public HtmlWindow get(String taskId,String fileId,String homeUrl) throws ErrorMessage{
		HtmlWindow process = new HtmlDiv(containerID);
		process.put(new HtmlValue(containerID+"r",containerID+"r",taskId));
		String msg = getPrompt(taskId);
		FlatTable ft=new FlatTable(ID,taskId);
		/**Select名字*/
		ft.putTh("导入信息", 0, 0);

		ft.putTd(getButton(),0,1);
		ft.setColWidth(0, "50",Length_Unit.percent);
		/**下载div*/
		if(fileId!=null){
			ft.putTh("下载导出文件", 1, 0);
			ft.putTd(getFileDownLoad(fileId,homeUrl),1,1);
		}
		ft.putExtend(new HtmlValue(this.refreshFlagID,"1"));
		process.put(ft.get());
		process.put(getShow(msg));
		process.setStyleWidth("610");
		process.setStyleHeight("400");
		process.put(setParam());
		process.put(new HtmlValue("h,_fileId","h,_fileId",fileId));
		if(!buttonShow){
			process.bind(refresh(taskId));
		}
		return process;
	}
	
	/**
	 * 空的下载div
	 * @return
	 * @throws ErrorMessage 
	 */
	private HtmlWindow getFileDownLoad(String fileId,String homeUrl) throws ErrorMessage{
		HtmlWindow downLoad = new HtmlDiv(ID+"download");
		downLoad.setVisibility(Visibility_Mode.Hidden);
		downLoad.put(new FileDownLoad(fileId,getFileName(fileId), homeUrl, File_Src.Upload).get());
		return downLoad;
	}

	/**
	 * 获取刷新任务界面
	 * @param taskId
	 * @param fileId下载文件Id
	 * @return
	 * @throws ErrorMessage
	 */
	public HtmlWindow getRefresh(String taskId,String fileId,String homeUrl) throws ErrorMessage{
		HtmlWindow process = new HtmlDiv();
		String msg = getPrompt(taskId);
		StringBuilder sp = new StringBuilder();
		sp.append("\\n");
		sp.append(msg);
		if(getStop(taskId)){
			String btScript = PopupScript.cancel("syspop"+TaskProcessMain.level);
			String download="";
			if(fileId!=null){
				download = "if($('"+ID+"download')){$('"+ID+"download').style.visibility='inherit';};";
			}
			process.bind("$('"+this.refreshFlagID+"').value='';" +
					"$('"+processInfoArearID+"').innerText=$('"+processInfoArearID+"').innerText+'\\n任务结束!';"+
					"$('"+processInfoArearID+"').scrollTop="+"$('"+processInfoArearID+"').scrollHeight;"+
					"$('"+this.returnBtId+"').className='bt';"+
					"$('"+this.returnBtId+"').onclick=function(){"+btScript+"};"
					+download);
		}else{
			process.bind("$('"+processInfoArearID+"').innerText=$('"+processInfoArearID+"').innerText+'"+sp.toString()+"';" +
					"$('"+processInfoArearID+"').scrollTop="+"$('"+processInfoArearID+"').scrollHeight;");
		}
		return process;
	}

	/**
	 * 导入内容显示文本框
	 * @param content  显示的字符串
	 * @return 导入进行程度信息
	 * @throws ErrorMessage
	 */
	private HtmlWindow getShow(String content) throws ErrorMessage{
		TextArea t = new TextArea(null,processInfoArearID,content,93,22);
		return t.get();
	}

	/**
	 * 根据任务ID取任务状态信息
	 * @param taskId 任务ID
	 * @return 导入状态提示信息
	 * @throws ErrorMessage
	 */
	private String getPrompt(String taskId) throws ErrorMessage{
		StringBuilder sb = new StringBuilder();
		TaskBase tb = Task.getTask(taskId);
		if(tb==null){
			tb =  Task.getTask("Buffer2MD:"+taskId);
		}
		if(tb!=null){
			ArrayList<String> status = tb.getStatusPrompt();
			if(status.size()>=1){
				//String currentStatus = status.get(status.size()-1);
				int s = 0;
				if(taskPrompt.getByKey(taskId)!=null){
					s = taskPrompt.getByKey(taskId);
				}
				for(int i=s;i<status.size();i++){
					sb.append(status.get(i)+"\\n");
				}
				/**保存最后一条记录*/
				taskPrompt.put(taskId, status.size());
			}
		}
		return sb.toString();
	}

	private boolean getStop(String taskId) throws ErrorMessage{
		TaskBase tb = Task.getTask(taskId);
		if(tb==null){
			tb =  Task.getTask("Buffer2MD:"+taskId);
		}
		if(tb==null){
			return true;
		}else{
			return tb.getFinished();
		}
	}

	/**
	 * 返回按钮，并刷导入任务管理页面
	 * @return
	 * @throws ErrorMessage
	 */
	private HtmlWindow getButton() throws ErrorMessage{
		HtmlWindow button = null;
		button = ButtonComp.get(this.returnBtId,mUser,"259",Button_Type.ReadOnly);
		return button;
	}

	/**
	 * 刷新脚本
	 * @param taskId 任务ID
	 * @return 刷新脚本字符串
	 */
	private String refresh(String taskId){
		//获取刷新任务状态界面脚本
		String script = AjxScript.getSpNoRefresh(containerID, //提交容器ID 
				TaskProcessMain.aId_Process_Refresh           //获取任务状态页面动作ID
				);
		//获取定时刷新界面脚本
		script = ScriptBind.ScriptInTime(script, //刷新页面脚本
				this.refreshFlagID,              //控制定时刷新停止的状态标志的页面容器ID
				TOOLS.intToString(time));        //定时刷新间隔
		return script;
	}

	/**
	 * 设置隐藏参数
	 * @return HtmlWindow
	 * @throws ErrorMessage
	 */
	private HtmlWindow setParam() throws ErrorMessage{
		HiddenParams hp = new HiddenParams(this.ID);
		hp.put(TaskProcessMain.refreshPararentCId, parentCid);
		hp.put(TaskProcessMain.refreshPararentAid, parentAid);
		return hp.get();
	}
	
	/**
	 * 导出文件名
	 * @param fileId 文件id
	 * @return
	 * @throws ErrorMessage
	 */
	private String getFileName(String fileId) throws ErrorMessage{
		String fileName = "点击下载导出文件";
		DataFilter filter = new DataFilter();
		filter.put(FileUpLoadStru.FILE_ID,fileId);
		OperatorResult or = Operator.get(FileUploadOptCode.Query_ByID, mUser.getUserID(), filter);
		if(TOOLS.exist(or)){
			SqlResult sr = or.getSelectResult();
			fileName = sr.get(0, FileUpLoadStru.FILE_NAME);
		}
		return fileName;
	}
}
